package service

import (
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/repository"
	"github.com/spf13/viper"
)

// -----------注销服务----------------


type DeregisterData struct {
	Type []string
	IP   string
	DC   string
}

// 接收前端注册服务信号，注册服务
func PostServiceDeregister(context *gin.Context) {
	var param DeregisterData
	err := context.BindJSON(&param) // 接收前端参数
	if err != nil {
		context.JSON(500, gin.H{"err": err})
		log.Printf("INFO: Register service failed")
		return
	}

	ipParts := strings.Split(param.IP, "\n")

	var deregisterState bool = false
	var outComeArr []string
	if len(param.Type) == 0 { // 如果Type为空则按照ip名称注销服务
		for _, valueIP := range ipParts {
			for i := 1; i <= viper.GetInt("consul_num."+param.DC); i++ {
				urlCheck := viper.GetString("consul." + param.DC + ".consul-" + strconv.Itoa(i))
				c := repository.CreateConsulClient(urlCheck + ":8085")
				state := c.DeregisterService(valueIP)
				deregisterState = deregisterState || state
			}
			if deregisterState {
				outComeArr = append(outComeArr, valueIP+" deregister success")
				deregisterState = false
			} else {
				outComeArr = append(outComeArr, valueIP+" deregister failes")
			}
		}
	} else { // 如果Type不为空则按照ip和类型注销服务
		for _, typeValue := range param.Type {
			for _, value := range ipParts {
				service_id := value + "-" + typeValue + "_exporter"
				for i := 1; i <= viper.GetInt("consul_num."+param.DC); i++ { // 循环检查consul集群中是否已经注册
					url := viper.GetString("consul." + param.DC + ".consul-" + strconv.Itoa(i))
					c := repository.CreateConsulClient(url + ":8085")
					state := c.DeregisterService(service_id)
					deregisterState = deregisterState || state
				}
				if deregisterState {
					outComeArr = append(outComeArr, value+" deregister success")
					deregisterState = false
				} else {
					outComeArr = append(outComeArr, value+" deregister failes")
				}
			}
		}
	}

	var deOutCome string // 返回信息
	for _, outcomeValue := range outComeArr {
		deOutCome = deOutCome + outcomeValue + "\n"
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{
		Code: 200,
		Data: deOutCome,
	}
	context.JSON(http.StatusOK, data)
}
